package com.ecy.quadratic.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ecy.quadratic.R;
import com.ecy.quadratic.beans.Comic;
import com.ecy.quadratic.beans.ComicDetail;
import com.ecy.quadratic.beans.SectionBean;
import com.ecy.quadratic.beans.support.ReadingSectionEvent;
import com.ecy.quadratic.component.DaggerComicDetailComponent;
import com.ecy.quadratic.manager.ComicCollectManager;
import com.ecy.quadratic.manager.EventManager;
import com.ecy.quadratic.reader.base.BaseActivity;
import com.ecy.quadratic.reader.component.AppComponent;
import com.ecy.quadratic.reader.utils.ScreenUtils;
import com.ecy.quadratic.ui.contract.ComicDetailContract;
import com.ecy.quadratic.ui.fragment.ComicDescriptionFragment;
import com.ecy.quadratic.ui.fragment.ComicSectionsFragment;
import com.ecy.quadratic.ui.presenter.ComicDetailPresenter;
import com.ecy.quadratic.widget.PagerSlidingTabStrip;
import com.yuyh.easyadapter.glide.GlideCompressTransform;
import com.yuyh.easyadapter.glide.GlideRoundTransform;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

public class ComicDetailActivity extends BaseActivity implements ComicDetailContract.View {
    private static final String INTENT_COMIC = "comic";
    private static final String INTENT_COMIC_DETAIL = "comic_detail";
    @Bind(R.id.tabs)
    PagerSlidingTabStrip mTabIndicator;
    @Bind(R.id.tab_viewpager)
    ViewPager mViewPager;
    @Bind(R.id.comic_detail_cover)
    ImageView mCoverIV;
    @Bind(R.id.start_read_llt)
    LinearLayout mStartReadllt;
    @Bind(R.id.description_read_tv)
    TextView mReadTV;
    @Bind(R.id.detail_reading_section_tv)
    TextView mReadingChapterTV;
    @Bind(R.id.add_collect_tv)
    TextView mAddCollectTV;
    @Bind(R.id.ivComicCover)
    ImageView mComicCoverIV;
    @Bind(R.id.comic_title_tv)
    TextView mComicTitleTV;
    @Bind(R.id.comic_author_tv)
    TextView mAuthorTV;
    @Bind(R.id.comic_recent_tv)
    TextView mRecentTV;
    @Inject
    ComicDetailPresenter mPresenter;
    private ComicDescriptionFragment mDescriptionFragment;
    private ComicSectionsFragment mSectionsFragment;
    private String mComicId = "";
    private SectionBean mReadingSection;
    private ComicDetail mComicDetail;
    private String mComicCover;
    private String mComicTitle;
    private String mComicAuthor;
    private String mComicRecentSection;


    public static void startActivity(Context context, Comic comic) {
        Intent intent = new Intent(context, ComicDetailActivity.class);
        intent.putExtra(INTENT_COMIC, comic);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, ComicDetail comic) {
        Intent intent = new Intent(context, ComicDetailActivity.class);
        intent.putExtra(INTENT_COMIC_DETAIL, comic);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_comic_detail;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerComicDetailComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initToolBar() {
    }

    @Override
    public void initData() {
        if (getIntent().hasExtra(INTENT_COMIC)) {
            Comic comic = (Comic) getIntent().getSerializableExtra(INTENT_COMIC);
            if (comic != null) {
                mComicId = comic.getId();
                mComicCover = comic.getImg();
                mComicTitle = comic.getTitle();
                mComicAuthor = comic.getAuthor();
                mComicRecentSection = comic.getRecentsection();
            }
        }
        if (getIntent().hasExtra(INTENT_COMIC_DETAIL)) {
            ComicDetail comicDetail = (ComicDetail) getIntent().getSerializableExtra(INTENT_COMIC_DETAIL);
            if (comicDetail != null) {
                mComicId = comicDetail.getId();
                mComicCover = comicDetail.getImg();
                mComicTitle = comicDetail.getTitle();
                mComicAuthor = comicDetail.getAuthor();
                mComicRecentSection = comicDetail.getRecentsection();
            }
        }


        EventBus.getDefault().register(this);
    }

    @Override
    public void configViews() {
        mComicTitleTV.setText(mComicTitle);
        mAuthorTV.setText(mComicAuthor);
        mRecentTV.setText(!TextUtils.isEmpty(mComicRecentSection) ? "更新至" + mComicRecentSection : "");
        if (TextUtils.isEmpty(mComicCover)) {
            mComicCover = "http://image.samanlehua.com/mh/" + mComicId + ".jpg";
        }
        Glide.with(this).load(mComicCover).diskCacheStrategy(DiskCacheStrategy.SOURCE).bitmapTransform(new GlideCompressTransform(this, ScreenUtils.getScreenWidth())/*,new BlurTransformation(this,25)*/).into(mCoverIV);
        Glide.with(this).load(mComicCover).diskCacheStrategy(DiskCacheStrategy.SOURCE).bitmapTransform(new GlideRoundTransform(this, 5)).into(mComicCoverIV);
        final ArrayList<String> titles = new ArrayList<>();
        titles.add("详情");
        titles.add("选集");
        final ArrayList<Fragment> fragments = new ArrayList<>();
        mDescriptionFragment = ComicDescriptionFragment.newInstance(mComicId);
        mSectionsFragment = ComicSectionsFragment.newInstance(mComicId);
        fragments.add(mDescriptionFragment);
        fragments.add(mSectionsFragment);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {  //注释掉，因为tablayout导航卡名字是根据这里进行绑定的，现在我们自定义了，不需要了
                return titles.get(position);
            }

        });
        mTabIndicator.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
            @Override
            public void onTabReselected(int position) {
                mViewPager.setCurrentItem(position);
            }
        });
        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        mViewPager.setPageMargin(pageMargin);
        mViewPager.setCurrentItem(0);
        mTabIndicator.setViewPager(mViewPager);
        mPresenter.attachView(this);
        mPresenter.getReadingSection(mComicId);
        mPresenter.getDetail(mComicId);

        mAddCollectTV.setVisibility(View.GONE);

    }

    @OnClick(R.id.add_collect_tv)
    public void addCollect() {
        boolean collect = !ComicCollectManager.getInstance().isCollected(mComicId);
        if (collect) {
            mAddCollectTV.setText("已关注");
            mAddCollectTV.setTextColor(Color.parseColor("#FF83c326"));
            mAddCollectTV.setBackgroundResource(R.drawable.cancel_collect_bg);
            mPresenter.addCollect(mComicDetail);
        } else {
            mAddCollectTV.setText("+ 关注");
            mAddCollectTV.setTextColor(Color.parseColor("#FFFFFFFF"));
            mAddCollectTV.setBackgroundResource(R.drawable.add_collect_bg);
            ComicCollectManager.getInstance().remove(mComicId);
        }

    }

    @Override
    public void showDetail(final ComicDetail detail) {
        hideLoading();
        mComicDetail = detail;
        EventManager.updateComicSections(detail);

        if (mReadingSection == null && detail.getSections() != null && detail.getSections().size() > 0) {
            mReadingChapterTV.setText(detail.getSections().get(0).getChapter_name());
            mStartReadllt.setVisibility(View.VISIBLE);
        }
        mReadTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SectionBean section = detail.getSections().get(0);
                ComicReadActivity.startActivity(ComicDetailActivity.this, detail.getId(), detail.getTitle(), detail.getImg(), detail.getSections(), mReadingSection != null ? mReadingSection : section);
            }
        });
        boolean collect = ComicCollectManager.getInstance().isCollected(mComicId);
        if (collect) {
            mAddCollectTV.setText("已关注");
            mAddCollectTV.setTextColor(Color.parseColor("#FF83c326"));
            mAddCollectTV.setBackgroundResource(R.drawable.cancel_collect_bg);
            mPresenter.addCollect(mComicDetail);
        } else {
            mAddCollectTV.setText("+ 关注");
            mAddCollectTV.setTextColor(Color.parseColor("#FFFFFFFF"));
            mAddCollectTV.setBackgroundResource(R.drawable.add_collect_bg);
            ComicCollectManager.getInstance().remove(mComicId);
        }
        mAddCollectTV.setVisibility(View.VISIBLE);
    }

    @Override
    public void updateReadingSection(SectionBean readingSection) {
        if (readingSection != null) {
            mReadingSection = readingSection;
            mReadingChapterTV.setText(readingSection.getChapter_name());
            mStartReadllt.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showLoadingView() {
        showLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateReadingSection(ReadingSectionEvent event) {
        if (event.readingSection != null) {
            mReadingSection = event.readingSection;
            mReadingChapterTV.setText(event.readingSection.getChapter_name());
            mStartReadllt.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showError() {
        if (mComicDetail == null) {
            showLoadingError();
            hideLoading();
        }
    }


    @Override
    public void complete() {
//        hideLoading();
    }

    @OnClick(R.id.rlt_loading_error)
    public void retry() {
        hideLoadingError();
        mPresenter.getDetail(mComicId);
    }

    @OnClick(R.id.title_back_iv)
    public void back() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        EventBus.getDefault().unregister(this);
    }

    public ComicDetailPresenter getPresenter() {
        return mPresenter;
    }

}